﻿using System;
using System.Collections.Generic;

namespace 链式编程2
{

    public delegate void Action<in T>(T obj);

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            List<IService> list = Host.CreateDefaultWebBuilder().Web((webBuilder) => 
            {
                webBuilder
                       .AddControllers(new MyController())
                       .AddControllers(new MyController2())
                       .AddServices(new MyService())
                       .AddServices(new MyService2());

            }).Services();

            Console.WriteLine(list.Count);

            Console.ReadKey();
        }


        

    }


    public static class Host
    {
        public static WebBuilder CreateDefaultWebBuilder()
        {
            return new WebBuilder();
        }
    }


    public interface IService
    {

    }

    public interface IController
    { 
    
    }

    public class MyController:IController { }

    public class MyController2 :IController { }

    public class MyService : IService
    {

    }

    public class MyService2 : IService
    {

    }

    public interface IWebBuilder
    {
        public IWebBuilder AddServices(IService service);
        public IWebBuilder AddControllers(IController controller);

        public List<IService> Services();
        public List<IController> Controllers();
    }


    public class WebBuilder : IWebBuilder
    {
        List<IService> services = new List<IService>();
        List<IController> controllers = new List<IController>();

        public IWebBuilder AddServices(IService service)
        {
            services.Add(service);
            return this;
        }

        public IWebBuilder AddControllers(IController controller)
        {
            controllers.Add(controller);
            return this;
        }



        public List<IService> Services()
        {
            return services;
        }


        public List<IController> Controllers()
        {
            return controllers;
        }
    }



    /// <summary>
    /// 对WebBuilder类进行扩展，扩展方法
    /// </summary>
    public static class WebBuilderExt
    {

        /// <summary>
        /// 扩展方法1，第一个参数是要被扩展的类，用this修饰这个是固定过的。
        /// 第二个参数开始才是方法的参数列表。
        /// </summary>
        /// <param name="webBuilder">被扩展的类</param>
        /// <param name="func">一个委托</param>
        /// <returns></returns>
        public static IWebBuilder Web(this IWebBuilder webBuilder, Action<IWebBuilder> action)
        {
            action(webBuilder);
            return webBuilder;
        }
    }
}
